<?php
/**
这里用于接受一些第三方提供的webhook
**/


namespace Apps\Controller;
use Think\Controller;

class WebhookController extends Controller {

    /**
      接受从 fir.im 触发过来的webhook请求
    */
    public function fromfirim(){
        $data = I();
        $name = $data['name'];
        $link = $data['link'];
        $build = $data['build'];
        $platform = strtolower($data['platform']);  //Android or ios 全部使用小写
        $changelog = $data['changelog'];
        $icon = $data['icon'];

        //根据应用的名称和平台来更新或者创建应用信息
        $countAppSql = "SELECT COUNT(*) AS c FROM gr_api.cm_version v WHERE v.app = '$name' AND v.device = '$platform'";

        $Model = new \Think\Model();

        $result = $Model->query($countAppSql);

        if($result === false){
          //查询错误
          //记录日志
          \Think\Log::record('WebhookController fromfirim ERROR: SQL:'.$countAppSql);
        }else{
          $count = intval($result[0]['c']);
          $now = time();
          if($count < 1){
            //系统中没有该应用,进行创建
            $insertAppSql = "INSERT INTO gr_api.cm_version(app,version,device,download,createAt,updateAt,delflag) VALUES('$name','$build','$platform','$link',$now,$now,0)";
            $result = $Model->execute($insertAppSql);
          }else{
            //更新系统中的应用
            $updateAppSql = "UPDATE gr_api.cm_version v SET VERSION = '$build',download = '$link',updateAt = $now WHERE v.app = '$name' AND v.device = '$platform'";
            $result = $Model->execute($updateAppSql);
          }
          if($result === 1){
            echo 'success';
            return;
          }
        }
        echo 'error';
    }
  }

 ?>
